package com.airsystem.pos.bengkel.service;

import java.util.LinkedList;
import java.util.List;

import org.hibernate.Session;

import com.airsystem.pos.bengkel.entity.JenisLayanan;
import com.airsystem.pos.bengkel.interfaces.IServices;
import com.airsystem.pos.bengkel.util.HibernateUtil;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class JenisLayananServices implements IServices<JenisLayanan> {
	private static final String SELECT = "FROM JenisLayanan WHERE %s LIKE :keyword";

	public void saveOrUpdate(JenisLayanan data) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			session.saveOrUpdate(data);
			session.flush();
		} finally {
			session.close();
		}
	}

	public void delete(JenisLayanan data) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			session.delete(data);
			session.flush();
		} finally {
			session.close();
		}
	}

	public Iterable<JenisLayanan> select(JenisLayanan data) {
		List<JenisLayanan> list = new LinkedList<JenisLayanan>();
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			StringBuffer LIKE = new StringBuffer("%");
			LIKE.append((data.getNama() == null ? "" : data.getNama()));
			LIKE.append("%");

			List<?> query = (List<?>) session.createQuery(String.format(SELECT, "nama")).setString("keyword", LIKE.toString()).list();

			for (Object result : query) {
				list.add((JenisLayanan) result);
			}
		} finally {
			session.close();
		}

		return list;
	}
}